package cn.melon.bz;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

import cn.melon.Helper.LoggerHelper;
import cn.melon.common.IConstant;
import cn.melon.common.Message;
import cn.melon.common.ModelType;
import cn.melon.mod.login.LoginControler;
import cn.melon.mod.login.UserInfo;

/**
 * 网络端实现
 * @author corvo
 */
public class IServerSrvImpl implements IServerSrv {
    
    public String TAG = LoggerHelper.makeLogTag(IServerSrvImpl.class);
    public Logger logger = LoggerHelper.serverLogger();
    
    private int port = IConstant.SERVER_PORT;
    private ServerSocket serverSocket;
    private boolean closed;

    public IServerSrvImpl() {

        logger.info(TAG + "开始监听 " + port + " 端口");

        serverSocket = null;
        try {
            
            serverSocket = new ServerSocket(port);
            closed = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void start() {
        new Thread(this).start();
    }
    
    @Override
    public void close() {
        
    }
    
    @Override
    public void run() {
        
        try {
            while (!closed && !serverSocket.isClosed()) {
                Socket s = serverSocket.accept();

                logger.info(TAG + "新进入客户端 " + s.getInetAddress());
                
                ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
                Message msg = (Message) ois.readObject();

                ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());

                ModelType type = msg.getModelType();

                logger.debug(TAG + msg.getData());
                
                if (type == ModelType.LOGIN) {      // 登录请求
                    LoginControler controller = new LoginControler(msg.getData()); // 只有login操作可以直接使用继承的类
                    UserInfo userInfo = controller.getUserInfo();

                    controller.makeResponse();
                    if (userInfo != null) {         // 登录成功
                        ClientThread ct = new ClientThread(s, userInfo);
                        ClientThreadMgr.add(userInfo.getUUID(), ct);
                        ct.start();
                    }

                    msg.setData(controller.getResponse());
                   
                    oos.writeObject(msg);
                    oos.flush();
                } else { // 其它模块请求, 此处不做处理
                    
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
